<template>
  <Modal
      :title="!dataForm._id ? '新增' : '修改'"
      :close-on-click-modal="false"
      :append-to-body="true"
      :lock-scroll="false"
      v-model="visible"

      :id="randomId">
    <Form
        v-if="
        typeof formTemplate.list !== 'undefined' && typeof formTemplate.config !== 'undefined'
      "
        class="form-build form-design"
        :label-position="formTemplate.config.labelPosition"
        :hide-required-asterisk="formTemplate.config.hideRequiredMark"
        :label-width="formTemplate.config.labelWidth"
        ref="dataForm"
        :model="dataForm"
    >
      <template
          v-for="(item,index) in formTemplate.list"
      >
        <FormItem v-if="
      !(item.options.hidden === true) &&
        ([
          'input',
          'textarea',
          'date',
          'time',
          'datePicker',
          'number',
          'radio',
          'checkbox',
          'select',
          'rate',
          'switch',
          'slider',
          'uploadImg',
          'uploadFile',
          'cascader'
        ].includes(item.type) || customList.includes(item.type) ) && dynamicVisibleItem(item)  "
                  :key="index"
                  :label="formTemplate.config.labelWidth > 0 ? item.label : null "
                  :rules="recordRules(item)"
                  :prop="item.rules && item.rules.length > 0 ? item.model : null"
                  :id="item.model" :name="item.model"
        >
          <BaseItem
              :models="dataForm"
              :formConfig="formTemplate.config"
              :renderPreview="renderPreview"
              :record="item"
              :disabled="disabled || (item.options.disabled && !item.options.dynamicDisabled )"
          />
        </FormItem>
      </template>


    </Form>


    <div slot="footer" class="mod-footer">
      <Button @click="visible = false">取消</Button>
      <Button :disabled="loading" v-if="!renderPreview" type="primary" @click="dataFormSubmit()">确定</Button>
    </div>

  </Modal>
</template>

<script>

import cloneDeep from 'lodash/cloneDeep';
import BaseItem from '../base';
import {dynamicFun} from '../../utils';

export default {
  name: 'TableAddOrUpdate',
  components: {

    BaseItem,
  },
  data() {
    return {
      randomId: '',
      loading: false,
      visible: false,
      dataForm: {
        _id: '',
        seq: 0,
      },
      dataRule: {},
    };
  },
  computed: {
    customList() {
      if (this.customComponents) {
        return this.customComponents.map(item => item.type);
      } else {
        return [];
      }
    },
  },
  inject: {
    customComponents: {
      from: 'customC',
      default: () => [],
    },
  },
  props: {

    formTemplate: {
      type: Object,
      default: () => ({}),
    },

    formConfig: {
      type: Object,
      default: () => ({}),
    },

    renderPreview: {
      type: Boolean,
      default: false,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  methods: {
    recordRules(record) {

      if (this.renderPreview) {
        return [];
      }
      const rules = record.rules;


      for (const t of rules) {

        if (t.vtype == 1 || t.vtype == 2) {
          t.validator = this.validatorFiled;
        }

        if (t.required && (record.type == 'input' || record.type == 'textarea')) {
          t.whitespace = true;
        }


        if (!t.trigger) {
          t.trigger = ['change', 'blur'];
        }
      }


      return rules;

    },
    dynamicVisibleItem(record) {

      if (!record.options || !record.options.dynamicVisible) {
        return true;
      }
      if (!record.options.dynamicVisibleValue) {
        return true;
      }
      let fstr = record.options.dynamicVisibleValue;

      const func = dynamicFun(fstr, this.dataForm);
      return func;
    },

    clearHiddenValue() {

      if (!this.formConfig || !this.formConfig.outputHidden) {

        const formdesign = document.getElementById(this.randomId);


        for (let key in this.dataForm) {
          if (key.indexOf('_label') > 0 || key == '_id' || key == 'seq') {
            continue;
          }

          const key_div = formdesign.querySelector('#' + key);
          if (!key_div) {

            delete this.dataForm[key];
            delete this.dataForm[key + '_label'];
          }
        }
      }
    },
    validatorFiled(rule, value, callback) {


      if (rule.vtype == 1) {

        if (!rule.pattern) {
          callback();
          return;
        }

        var patt1 = new RegExp(rule.pattern);


        if (patt1.test(value)) {
          callback();
        } else {
          callback(new Error(rule.message));
        }

        return;
      } else if (rule.vtype == 2) {

        const script = rule.script;


        const fvalue = dynamicFun(script, this.dataForm);

        if (!fvalue) {
          callback(new Error(rule.message));
        } else {
          callback();
        }


      }


    },

    init(data) {
      this.randomId = 'sxfw_table_dialog' + parseInt(Math.random() * 1000000, 10);
      this.visible = true;
      this.dataForm._id = null;
      if (data) {

        for (var i in data) {
          this.dataForm[i] = data[i];
        }
      } else {


        const d = {};
        this.formTemplate.list.forEach(item => {
          if (item.options.defaultValue) {
            d[item.model] = item.options.defaultValue;
          } else {
            d[item.model] = null;
          }
        });

        this.dataForm = {_id: null, seq: 0, ...d};

        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields();
        });
      }


    },

    dataFormSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.clearHiddenValue();
          if (!this.dataForm._id) {

            const id = new Date().getTime() * 10 + parseInt(Math.random() * 100,10);
            this.dataForm._id = id;
            this.$emit('formAdd', cloneDeep(this.dataForm));
          } else {
            this.$emit('formUpdate', cloneDeep(this.dataForm));
          }
          this.loading = false;
          this.visible = false;
        }
      });


    },
  },
};
</script>
